package com.javafactroy.kunlong.bip.icp.message.data.netty.handler.server;


import io.netty.channel.ChannelHandler;
import org.springframework.stereotype.Component;
import com.javafactroy.kunlong.bip.icp.factory.AppMessageFactory;
import com.javafactroy.kunlong.bip.icp.message.base.iface.IMessage;
import com.javafactroy.kunlong.bip.icp.message.dxp.base.DxpMsg;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Component
@ChannelHandler.Sharable // 标注一个channel handler可以被多个channel安全地共享
@Slf4j
public class BipServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

       IMessage in = (IMessage) msg;
        log.info("BipServerHandler received: " + in.toString());

        DxpMsg resp =( DxpMsg ) AppMessageFactory.execute(in);
        resp.getHeader().setMsgId(Integer.valueOf(in.getMessageId()));
        ctx.write(resp);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}